import { Component, OnInit, Input } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UserService } from 'src/app/core/service/user.service';

@Component({
  selector: 'app-edit-group-user',
  templateUrl: './edit-group-user.component.html',
  styleUrls: ['./edit-group-user.component.scss']
})
export class EditGroupUserComponent implements OnInit {
  @Input() groupName: string;
  @Input() groupUuid: string;
  groupEditUserForm: FormGroup;
  radioValue = '0';
  isAllocation = true;
  defaultValue = 0;
  info = {};

  constructor(
    private modal: NzModalRef,
    private message: NzMessageService,
    private userService: UserService,
    fb: FormBuilder
  ) {
    this.groupEditUserForm = fb.group({
      groupName: [null, Validators.compose([Validators.required])],
      autoScaLicense: [null, Validators.compose([Validators.required])]
    });
  }

  ngOnInit() {
    this.groupEditUserForm.patchValue({
      groupName: this.groupName,
    });
  }

  changeGroupUserModal() {
    console.log('提交', this.groupEditUserForm.controls.autoScaLicense.valid);
    // tslint:disable-next-line:forin
    for (const c in this.groupEditUserForm.controls) {
      this.groupEditUserForm.controls[c].markAsTouched();
    }

    if (this.groupEditUserForm.valid) {
      this.info = {
        groupName: this.groupEditUserForm.controls.groupName.value,
        autoScaLicense: this.groupEditUserForm.controls.autoScaLicense.value,
        groupUuid: this.groupUuid
      };
      this.editService(this.info);
    } else {
      this.message.error('表单校验失败', { nzDuration: 10000 });
    }
  }

  private editService(info: any) {
    this.userService.updateGroupUser(info)
      .subscribe((updateGroupUser) => {
        if (updateGroupUser.status) {
          this.message.success('修改成功!', {
            nzDuration: 10000
          });
          this.modal.destroy();
        } else {
          this.message.error('修改失败!请检查后重新填写', {
            nzDuration: 10000
          });
        }
      });
  }

  destroyModal(): void {
    this.modal.destroy({ data: 'this the result data' });
  }

  /**
   * 判断小组名称是否重复
   */
  isGroupNameRepeat() {
    console.log('=== Janine.isGroupNameRepeat().groupName ===>', this.groupEditUserForm.controls.groupName.value);
    if (this.groupEditUserForm.controls.groupName.value) {
      this.userService.isGroupNameRepeat(this.groupEditUserForm.controls.groupName.value, this.groupUuid)
        .subscribe((data) => {
          console.log(data);
          if (data.status === 3) {
            this.message.error(data.msg, {
              nzDuration: 10000
            });
          }
          if (data.status === 1) {
            this.message.success('小组名称可用', {
              nzDuration: 10000
            });
          }
        });
    }
  }
}
